// 棋盘类
class Board {
    constructor(game) {
        this.game = game;
        this.boardData = [];
        this.boardSize = CONFIG.boardSize;
    }

    // 初始化棋盘
    initBoard(initialBoard) {
        this.boardData = [];
        
        // 复制初始棋盘数据
        for (let row = 0; row < this.boardSize; row++) {
            this.boardData[row] = [];
            for (let col = 0; col < this.boardSize; col++) {
                this.boardData[row][col] = initialBoard[row][col];
            }
        }
        
        // 渲染棋盘
        this.renderBoard();
    }

    // 渲染棋盘
    renderBoard() {
        const gameBoard = document.getElementById('game-board');
        gameBoard.innerHTML = '';
        
        // 创建格子
        for (let row = 0; row < this.boardSize; row++) {
            for (let col = 0; col < this.boardSize; col++) {
                const cell = document.createElement('div');
                cell.className = 'cell';
                cell.dataset.row = row;
                cell.dataset.col = col;
                
                // 添加元素
                const elementType = this.boardData[row][col];
                const elementDiv = document.createElement('div');
                elementDiv.className = CONFIG.elementClasses[elementType];
                cell.appendChild(elementDiv);
                
                // 如果是木箱，显示生命值
                if (elementType === CONFIG.elementTypes.BOX) {
                    const valueDiv = document.createElement('div');
                    valueDiv.className = 'box-value';
                    valueDiv.textContent = CONFIG.boxHealth;
                    cell.appendChild(valueDiv);
                }
                
                // 如果是Boss，显示生命值
                if (elementType === CONFIG.elementTypes.BOSS) {
                    const healthDiv = document.createElement('div');
                    healthDiv.className = 'boss-health';
                    healthDiv.textContent = this.game.bossHealth;
                    cell.appendChild(healthDiv);
                }
                
                gameBoard.appendChild(cell);
            }
        }
    }

    // 获取指定位置的格子类型
    getCell(row, col) {
        if (row < 0 || row >= this.boardSize || col < 0 || col >= this.boardSize) {
            return null;
        }
        return this.boardData[row][col];
    }

    // 设置指定位置的格子类型
    setCell(row, col, type) {
        if (row < 0 || row >= this.boardSize || col < 0 || col >= this.boardSize) {
            return;
        }
        this.boardData[row][col] = type;
    }

    // 更新棋盘显示
    updateBoard() {
        // 更新每个格子的显示
        for (let row = 0; row < this.boardSize; row++) {
            for (let col = 0; col < this.boardSize; col++) {
                const cell = document.querySelector(`.cell[data-row="${row}"][data-col="${col}"]`);
                if (!cell) continue;
                
                // 清空格子内容
                cell.innerHTML = '';
                
                // 添加元素
                const elementType = this.boardData[row][col];
                const elementDiv = document.createElement('div');
                elementDiv.className = CONFIG.elementClasses[elementType];
                cell.appendChild(elementDiv);
                
                // 如果是木箱，显示生命值
                if (elementType === CONFIG.elementTypes.BOX) {
                    const valueDiv = document.createElement('div');
                    valueDiv.className = 'box-value';
                    valueDiv.textContent = CONFIG.boxHealth;
                    cell.appendChild(valueDiv);
                }
                
                // 如果是Boss，显示生命值
                if (elementType === CONFIG.elementTypes.BOSS) {
                    const healthDiv = document.createElement('div');
                    healthDiv.className = 'boss-health';
                    healthDiv.textContent = this.game.bossHealth;
                    cell.appendChild(healthDiv);
                }
                
                // 如果是主角所在位置，添加主角样式
                if (elementType === CONFIG.elementTypes.PLAYER) {
                    cell.classList.add('player-cell');
                } else {
                    cell.classList.remove('player-cell');
                }
            }
        }
    }

    // 添加带动画效果的元素填充
    fillCellWithAnimation(row, col, elementType) {
        const cell = document.querySelector(`.cell[data-row="${row}"][data-col="${col}"]`);
        if (!cell) return Promise.resolve(); // 立即解决Promise以避免等待
        
        // 标记为正在动画
        cell.classList.add('animating');
        
        // 清空格子内容
        cell.innerHTML = '';
        
        // 更新数据
        this.boardData[row][col] = elementType;
        
        // 添加元素并应用动画
        const elementDiv = document.createElement('div');
        elementDiv.className = CONFIG.elementClasses[elementType] + ' element-appear';
        cell.appendChild(elementDiv);
        
        // 如果是木箱，显示生命值
        if (elementType === CONFIG.elementTypes.BOX) {
            const valueDiv = document.createElement('div');
            valueDiv.className = 'box-value';
            valueDiv.textContent = CONFIG.boxHealth;
            cell.appendChild(valueDiv);
        }
        
        return new Promise(resolve => {
            // 使用animationend事件而不是setTimeout
            elementDiv.addEventListener('animationend', () => {
                elementDiv.classList.remove('element-appear');
                cell.classList.remove('animating');
                resolve();
            }, { once: true }); // 只触发一次
            
            // 作为备用，如果animationend不触发，500ms后也会解除
            setTimeout(() => {
                elementDiv.classList.remove('element-appear');
                cell.classList.remove('animating');
                resolve();
            }, CONFIG.animationDuration + 50);
        });
    }

    // 检查指定位置是否是主角
    isPlayerPosition(row, col) {
        return this.boardData[row][col] === CONFIG.elementTypes.PLAYER;
    }
    
    // 清除所有连接
    clearAllConnections() {
        // 移除所有高亮和箭头
        const cells = document.querySelectorAll('.cell.selected');
        cells.forEach(cell => cell.classList.remove('selected'));
        this.clearAllArrows();
        
        // 清空连接数据
        this.game.connectedCells = [];
        this.game.isConnecting = false;
        this.game.attackPower = 0;
        this.game.currentConnType='Free'
        
        // 更新UI显示
        this.game.ui.updateUI();
    }

    // 绘制连接箭头
    drawConnectionArrow(fromRow, fromCol, toRow, toCol) {
        const gameBoard = document.getElementById('game-board');
        const arrow = document.createElement('div');
        arrow.className = 'connection-arrow';
        
        // 获取单元格元素
        const fromCell = gameBoard.querySelector(`[data-row="${fromRow}"][data-col="${fromCol}"]`);
        const toCell = gameBoard.querySelector(`[data-row="${toRow}"][data-col="${toCol}"]`);
        
        // 获取单元格相对于游戏板的位置
        const fromCellRect = fromCell.getBoundingClientRect();
        const toCellRect = toCell.getBoundingClientRect();
        const gameBoardRect = gameBoard.getBoundingClientRect();
        
        // 计算相对位置（相对于游戏板）
        const fromX = fromCell.offsetLeft + (fromCell.offsetWidth / 2);
        const fromY = fromCell.offsetTop + (fromCell.offsetHeight / 2);
        const toX = toCell.offsetLeft + (toCell.offsetWidth / 2);
        const toY = toCell.offsetTop + (toCell.offsetHeight / 2);
        
        // 计算箭头属性
        const dx = toX - fromX;
        const dy = toY - fromY;
        const angle = Math.atan2(dy, dx) * 180 / Math.PI;
        const length = Math.sqrt(dx * dx + dy * dy);
        
        // 设置箭头样式
        Object.assign(arrow.style, {
            position: 'absolute',
            left: `${fromX}px`,
            top: `${fromY}px`,
            width: `${length}px`,
            transform: `rotate(${angle}deg) translateY(-50%)`
        });
        
        gameBoard.appendChild(arrow);
    }

    // 清除所有箭头
    clearAllArrows() {
        const arrows = document.querySelectorAll('.connection-arrow');
        arrows.forEach(arrow => arrow.remove());
    }
}